import Vue from "vue";
import VueRouter from "vue-router";
import jwtDecode from "jwt-decode";
import Home from "../views/Home.vue";

const Users = () =>
  import(/* webpackChunkName: "users" */ "../views/users/Users.vue");
const Roles = () =>
  import(/* webpackChunkName: "users" */ "../views/rights/Roles.vue");
const Rights = () =>
  import(/* webpackChunkName: "users" */ "../views/rights/Rights.vue");
const Goods = () =>
  import(/* webpackChunkName: "users" */ "../views/goods/GoodsList.vue");
const GoodsAdd = () =>
  import(/* webpackChunkName: "users" */ "../views/goods/GoodsAdd.vue");
const Params = () =>
  import(/* webpackChunkName: "users" */ "../views/goods/Params.vue");
const Categories = () =>
  import(/* webpackChunkName: "users" */ "../views/goods/Categories.vue");
const Orders = () =>
  import(/* webpackChunkName: "users" */ "../views/orders/Orders.vue");
const Reports = () =>
  import(/* webpackChunkName: "users" */ "../views/reports/Reports.vue");

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "home",
    component: Home,
    children: [
      { path: "/users", component: Users },
      { path: "/roles", component: Roles },
      { path: "/rights", component: Rights },
      { path: "/goods", component: Goods },
      { path: "/goods/add", component: GoodsAdd,meta:{parentPath:"/goods"} },
      { path: "/params", component: Params },
      { path: "/categories", component: Categories },
      { path: "/orders", component: Orders },
      { path: "/reports", component: Reports },
    ],
  },
  {
    path: "/login",
    name: "login",
    component: () =>
      import(/* webpackChunkName: "login" */ "../views/Login.vue"),
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

router.beforeEach((to, from, next) => {
  //如果访问登录页，就放行
  if (to.path === "/login") return next();
  let token = sessionStorage.getItem("token");
  if (token) {
    //判断是否过期
    let { exp } = jwtDecode(token);
    let nowtime = Math.floor(new Date().getTime() / 1000);

    if (exp - nowtime >= 0) {
      next();
    } else {
      next("/login");
    }
  } else {
    next("/login");
  }
});

export default router;
